package com.china08.yxyapi.service.yxyresource.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.elasticsearch.index.query.RegexpQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.SystemConstant;
import com.china08.yxyapi.api.manage.tec.teaching.resource.myCollect.MyCollectSrhController;
import com.china08.yxyapi.api.manage.tec.teaching.resource.myCollect.MyCollectSrhController.RespModel;
import com.china08.yxyapi.api.manage.tec.teaching.resource.myresource.ResourceUploadController.ResourceReqModel;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.db.res.YxyResFormat;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceBookContent;
import com.china08.yxyapi.entity.db.res.YxyResType;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserFavor;
import com.china08.yxyapi.model.mg.YxyUserFavorModel;
import com.china08.yxyapi.model.resource.SearchResourceModel;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResFormatRepository;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResTypeRepository;
import com.china08.yxyapi.repository.mg.YxyUserFavorRepository;
import com.china08.yxyapi.service.yxyresource.YxyResourceService;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.MongodbUtil;
import com.china08.yxyapi.util.YxyResUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

@Service
public class YxyResourceServiceImpl implements YxyResourceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyResourceServiceImpl.class);

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResResourceRepository yrrr;

    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    private YxyResTypeRepository yrtr;

    @Autowired
    private YxyResFormatRepository yrfr;

    @Autowired
    private YxyResBookRepository yrbr;

    @Autowired
    private YxyResBookContentsRepository yrbcr;

    @Autowired
    private YxyUserFavorRepository yufr;

    @Autowired
    private MongoTemplate mt;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private YxyResResourceBookContentRepository yxyResResourceBookContentRepository;

    @Override
    public Page<ElasticYxyResResource> homeIndexResourceArea(String areaId, Integer resType, String phase,
            String subject, String version, String bookcontent, String semester, String bookId, String type,
            String format, String keyword, Type typeSearch, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        BoolQueryBuilder minBoolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // 是否云校资源 isYxYunRes
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 0);
        // boolQueryBuilder.must(builderisYxYunRes);

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        boolQueryBuilder.must(areBuilder);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }
        // 如果是查询微课
        if ("yx14".equals(type) || StringUtils.isBlank(type) || "all".equals(type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
                // 目录不为空 根据目录找到知识点
            } else {
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
            }
            minBoolQueryBuilder.should(knoBoolQueryBuilder);
        }
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                resBoolQueryBuilder.must(builder);
            }
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }

        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        // 资源
        minBoolQueryBuilder.should(resBoolQueryBuilder);
        boolQueryBuilder.must(minBoolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> homeIndexResourceSchool(String SchoolId, Integer resType, String phase,
            String subject, String version, String bookcontent, String semester, String bookId, String type,
            String format, String keyword, Type typeSearch, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        BoolQueryBuilder minBoolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope 本校或者是教育云
        BoolQueryBuilder viewScopeOrQuery = new BoolQueryBuilder();
        TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 1);
        TermQueryBuilder builderviewScope2 = new TermQueryBuilder("viewScope", 2);
        viewScopeOrQuery.should(builderviewScope1);
        viewScopeOrQuery.should(builderviewScope2);
        boolQueryBuilder.must(viewScopeOrQuery);

        Assert.notNull(StringUtils.defaultIfBlank(SchoolId, null), "请关联学校");
        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", SchoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 是否云校资源 isYxYunRes 不是云校资源
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 0);
        // boolQueryBuilder.must(builderisYxYunRes);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        //
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                resBoolQueryBuilder.must(builder);
            }
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }

        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }
        minBoolQueryBuilder.should(resBoolQueryBuilder);
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }

        // 如果是查询微课
        if ("yx14".equals(type) || StringUtils.isBlank(type) || "all".equals(type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
                // 目录不为空 根据目录找到知识点
            } else {
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
            }
            minBoolQueryBuilder.should(knoBoolQueryBuilder);
        }

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        boolQueryBuilder.must(minBoolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> homeIndexResourceYun(Integer resType, String phase, String subject,
            String version, String bookcontent, String semester, String bookId, String type, String format,
            String keyword, Type typeSearch, Integer flag, Integer restype, Pageable pageable) {

        long start = System.currentTimeMillis();
        //
        BoolQueryBuilder maxBoolQueryBuilder = new BoolQueryBuilder();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 是否是vip
        // 1.vip
        if (flag == 1) {
            TermQueryBuilder builderIsVip = new TermQueryBuilder("isVip", true);
            maxBoolQueryBuilder.must(builderIsVip);
            // 免费
        } else if (flag == 2) {
            TermQueryBuilder builderIsVip = new TermQueryBuilder("isVip", true);
            maxBoolQueryBuilder.mustNot(builderIsVip);
        }
        // 是否是 精品资源
        if (restype == 0) {
            TermQueryBuilder builderJp = new TermQueryBuilder("isHighQualityYx", 1);
            maxBoolQueryBuilder.must(builderJp);
        }

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        maxBoolQueryBuilder.must(builderDel);
        maxBoolQueryBuilder.must(new TermQueryBuilder("isYxView", 1));
        //
        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        maxBoolQueryBuilder.must(builderStatusYes1);

        // 资源类型
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();

        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", bookcontent);
            resBoolQueryBuilder.must(builder);
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }
        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }
        //
        boolQueryBuilder.should(resBoolQueryBuilder);

        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            maxBoolQueryBuilder.must(builder);
        }
        // 如果是查询微课
        if (StringUtils.isBlank(type) || StringUtils.equals("all", type) || StringUtils.equals("yx14", type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                long startXX = System.currentTimeMillis();
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
                long endXX = System.currentTimeMillis();
                LOGGER.info(("根据书籍找知识点时间为：" + ((endXX - startXX) / 1000)));
                // 目录不为空 根据目录找到知识点
            } else {
                long startAA = System.currentTimeMillis();
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
                long endAA = System.currentTimeMillis();
                LOGGER.info("根据目录找知识点时间为:" + ((endAA - startAA) / 1000));
            }
            boolQueryBuilder.should(knoBoolQueryBuilder);
        }
        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            maxBoolQueryBuilder.must(builder);
        }
        maxBoolQueryBuilder.must(boolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(maxBoolQueryBuilder, keyword, pageable);
        long end = System.currentTimeMillis();
        LOGGER.info("查询总时长为：" + ((end - start) / 1000));
        return page;
    }

    @Override
    public List<ElasticYxyResResource> getResource(List<String> bookcontent) {
        BoolQueryBuilder maxBoolQueryBuilder = new BoolQueryBuilder();
        // 微课知识点
        BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
        // 拿到所有目录id
        // 根据目录Id拿到所有的知识点Id
        if (CollectionUtils.isNotEmpty(bookcontent)) {
            List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(bookcontent);
            Set<Integer> set = new HashSet<>(list1);
            List<Integer> list = new ArrayList<>(set);
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            // 刨除已删除的
            TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
            knoBoolQueryBuilder.must(builderDel);
            // 微课判断
            TermQueryBuilder builderTypeId = new TermQueryBuilder("typeId", "yx14");
            knoBoolQueryBuilder.must(builderTypeId);
            // ##
            // 在云校显示
            TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView", 1);
            maxBoolQueryBuilder.must(builderisviewYun);
            //

            // 刨除是私有的 和在学校展示的
            int[] arr = { 0, 1 };
            TermsQueryBuilder builderViewScop = new TermsQueryBuilder("viewScope", arr);
            maxBoolQueryBuilder.mustNot(builderViewScop);

            // 只查询审核已通过的
            TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
            maxBoolQueryBuilder.must(builderStatusYes1);
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
        }
        maxBoolQueryBuilder.must(knoBoolQueryBuilder);
        List<ElasticYxyResResource> els = this.getList(maxBoolQueryBuilder);
        return els;
    }

    @Override
    public Page<ElasticYxyResResource> getPageEs(BoolQueryBuilder maxBoolQueryBuilder, String keyword,
            Pageable pageable) {
        BoolQueryBuilder b1 = new BoolQueryBuilder();
        b1.must(maxBoolQueryBuilder);
        Page<ElasticYxyResResource> page = null;
        if (StringUtils.isNotBlank(keyword)) {
            if (StringUtils.isNotBlank(keyword) && !StringUtils.equals("all", keyword)) {
                b1 = keyword(keyword, 1, b1);
            }
            page = getPage(b1, pageable);
            if (page.getContent().size() == 0 && StringUtils.isNotBlank(keyword)) {
                BoolQueryBuilder b2 = new BoolQueryBuilder();
                b2.must(maxBoolQueryBuilder);
                b2 = keyword(keyword, 2, b2);
                SearchQuery query2 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b2).build();
                page = et.queryForPage(query2, ElasticYxyResResource.class);
                if (page.getContent().size() == 0) {
                    BoolQueryBuilder b4 = new BoolQueryBuilder();
                    b4.must(maxBoolQueryBuilder);
                    b4 = keyword(keyword, 4, b4);
                    SearchQuery query4 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b4).build();
                    page = et.queryForPage(query4, ElasticYxyResResource.class);
                    if (page.getContent().size() == 0) {
                        BoolQueryBuilder b3 = new BoolQueryBuilder();
                        b3.must(maxBoolQueryBuilder);
                        b3 = keyword(keyword, 3, b3);
                        SearchQuery query3 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b3)
                                .build();
                        page = et.queryForPage(query3, ElasticYxyResResource.class);
                    }
                }
            }
        } else {
            page = getPage(b1, pageable);
        }
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        LOGGER.info("======================ES====================ES========================");
        LOGGER.info(boolQueryBuilder.toString());
        LOGGER.info("======================ES====================ES========================");
        Page<ElasticYxyResResource> page = et.queryForPage(query, ElasticYxyResResource.class);
        return page;
    }

    @Override
    public List<ElasticYxyResResource> getList(BoolQueryBuilder boolQueryBuilder) {
        // SortBuilder sortBuilder = new
        // FieldSortBuilder("pv").order(SortOrder.DESC);
        Pageable pageable = new PageRequest(0, 10, Direction.DESC, "pv");
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageable).build();
        List<ElasticYxyResResource> list = et.queryForList(query, ElasticYxyResResource.class);
        return list;
    }

    @Override
    public List<ElasticYxyResResource> getAll(BoolQueryBuilder boolQueryBuilder) {
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        List<ElasticYxyResResource> list = et.queryForList(query, ElasticYxyResResource.class);
        return list;
    }

    @Override
    public List<ElasticYxyResResource> getListTop(BoolQueryBuilder boolQueryBuilder, int size, String order) {
        // SortBuilder sortBuilder = new
        // FieldSortBuilder("pv").order(SortOrder.DESC);
        Pageable pageable = new PageRequest(0, size, Direction.DESC, order);
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageable).build();
        List<ElasticYxyResResource> list = et.queryForList(query, ElasticYxyResResource.class);
        return list;
    }

    @Override
    @Transactional
    public void audit(Integer auditStatus, String[] ids, String content, String userId, String userNick,
            String schoolId, String schoolName) {
        Assert.isTrue(ids.length > 0, "请选择要处理的资源");
        List<YxyResResource> list = yrrr.findByIdIn(Arrays.asList(ids));
        for (YxyResResource yxyResResource : list) {
            yxyResResource.setStatus(auditStatus);
            yxyResResource.setLastModifiedBy(userId);
            yxyResResource.setAuditUserId(userId);
            yxyResResource.setAuditUserName(userNick);
            yxyResResource.setAuditSchoolId(schoolId);
            yxyResResource.setAuditSchoolName(schoolName);
            yxyResResource.setRemark(content);
            yrrr.saveAndFlush(yxyResResource);
        }
    }

    @Override
    public List<ElasticYxyResResource> homeIndexResourceRecommendArea(String areaId, String bookContent, String book) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // 是否云校资源 isYxYunRes
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 0);
        // boolQueryBuilder.must(builderisYxYunRes);

        // 区域
        // 教育云所在区域
        if (StringUtils.isNotBlank(areaId)) {
            BoolQueryBuilder areBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
            TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
            TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
            areBuilder.should(builderprovince);
            areBuilder.should(buildercity);
            areBuilder.should(builderdistrict);
            boolQueryBuilder.must(areBuilder);
        }

        // 刨除微课的
        // TermQueryBuilder builderWeike = new TermQueryBuilder("typeId",
        // "yx14");
        // boolQueryBuilder.mustNot(builderWeike);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 目录
        if (StringUtils.isNotBlank(bookContent) && !StringUtils.equals("all", bookContent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookContent);
            BoolQueryBuilder tocBuilder = new BoolQueryBuilder();
            for (String string : tocIdList) {
                TermQueryBuilder buildertocId = new TermQueryBuilder("bookContentIdList", string);
                tocBuilder.should(buildertocId);
            }
            boolQueryBuilder.should(tocBuilder);
        } else {
            TermQueryBuilder buildertocId = new TermQueryBuilder("bookIdList", book);
            boolQueryBuilder.should(buildertocId);
        }
        // 微课知识点
        BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isBlank(bookContent)) {
            // 根据课本Id拿到所有目录id
            List<String> listcoContents = yrbcr.findIdByBookId(book);
            // 根据目录Id拿到所有的知识点Id
            Set<Integer> set = new HashSet<>();
            List<Integer> list = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(listcoContents)) {
                List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                set = new HashSet<>(list1);
                list = new ArrayList<>(set);
            }
            if (CollectionUtils.isEmpty(list)) {
                list.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
            // 目录不为空 根据目录找到知识点
        } else {
            List<String> list = yxyResUtil.findTocByTocParent(bookContent);
            List<Integer> knowIds = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(list)) {
                List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                        .findByBookContentIdIn(list);
                knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(knowIds)) {
                knowIds.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
        }

        boolQueryBuilder.should(knoBoolQueryBuilder).minimumNumberShouldMatch(1);
        List<ElasticYxyResResource> list = getList(boolQueryBuilder);
        return list;
    }

    @Override
    public List<ElasticYxyResResource> getRecommendResource(List<Integer> knowIds) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // 是否云校资源 isYxYunRes
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 刨除微课的
        // TermQueryBuilder builderWeike = new TermQueryBuilder("typeId",
        // "yx14");
        // boolQueryBuilder.mustNot(builderWeike);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);
        BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
        if (CollectionUtils.isEmpty(knowIds)) {
            knowIds.add(0000);
        }
        BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
        TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
        TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
        TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
        knoBuilder.should(builderknowOne);
        knoBuilder.should(builderknowTwo);
        knoBuilder.should(builderknowThree);
        knoBoolQueryBuilder.must(knoBuilder);

        boolQueryBuilder.should(knoBoolQueryBuilder).minimumNumberShouldMatch(1);
        List<ElasticYxyResResource> list = getList(boolQueryBuilder);
        return list;
    }

    @Override
    public List<ElasticYxyResResource> homeIndexResourceRecommendSchool(String schoolId, String bookContent,
            String book) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope 本校
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 1);
        boolQueryBuilder.must(builderviewScope);

        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchoolId);

        // // 是否云校资源 isYxYunRes 不是云校资源
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 0);
        // boolQueryBuilder.must(builderisYxYunRes);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 刨除微课的
        // TermQueryBuilder builderWeike = new TermQueryBuilder("typeId",
        // "yx14");
        // boolQueryBuilder.mustNot(builderWeike);

        // 目录
        if (StringUtils.isNotBlank(bookContent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookContent);
            BoolQueryBuilder tocBuilder = new BoolQueryBuilder();
            for (String string : tocIdList) {
                TermQueryBuilder buildertocId = new TermQueryBuilder("bookContentIdList", string);
                tocBuilder.should(buildertocId);
            }
            boolQueryBuilder.should(tocBuilder);
        } else {
            TermQueryBuilder buildertocId = new TermQueryBuilder("bookIdList", book);
            boolQueryBuilder.should(buildertocId);
        }
        // 微课知识点
        BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isBlank(bookContent)) {
            // 根据课本Id拿到所有目录id
            List<String> listcoContents = yrbcr.findIdByBookId(book);
            // 根据目录Id拿到所有的知识点Id
            Set<Integer> set = new HashSet<>();
            List<Integer> list = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(listcoContents)) {
                List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                set = new HashSet<>(list1);
                list = new ArrayList<>(set);
            }
            if (CollectionUtils.isEmpty(list)) {
                list.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
        } else {
            List<String> list = yxyResUtil.findTocByTocParent(bookContent);
            List<Integer> knowIds = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(list)) {
                List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                        .findByBookContentIdIn(list);
                knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(knowIds)) {
                knowIds.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
        }

        boolQueryBuilder.should(knoBoolQueryBuilder).minimumNumberShouldMatch(1);
        List<ElasticYxyResResource> list = getList(boolQueryBuilder);
        return list;
    }

    @Override
    public List<ElasticYxyResResource> homeIndexResourceRecommendYun(String bookContent, String book) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // ##
        // 是云校资源 isYxYunRes
        // BoolQueryBuilder boolYun = new BoolQueryBuilder();
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 1);
        // boolYun.should(builderisYxYunRes);
        // // 或者在云校显示
        // TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView",
        // 1);
        // boolYun.should(builderisviewYun);
        boolQueryBuilder.must(new TermQueryBuilder("isYxView", 1));
        //

        // 刨除是私有的 和在学校展示的
        int[] arr = { 0, 1 };
        TermsQueryBuilder builderViewScop = new TermsQueryBuilder("viewScope", arr);
        boolQueryBuilder.mustNot(builderViewScop);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // // 刨除微课的
        // TermQueryBuilder builderWeike = new TermQueryBuilder("typeId",
        // "yx14");
        // boolQueryBuilder.mustNot(builderWeike);

        // 目录
        if (StringUtils.isNotBlank(bookContent) && !StringUtils.equals("all", bookContent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookContent);
            BoolQueryBuilder tocBuilder = new BoolQueryBuilder();
            for (String string : tocIdList) {
                TermQueryBuilder buildertocId = new TermQueryBuilder("bookContentIdList", string);
                tocBuilder.should(buildertocId);
            }
            boolQueryBuilder.should(tocBuilder);
        } else {
            TermQueryBuilder buildertocId = new TermQueryBuilder("bookIdList", book);
            boolQueryBuilder.should(buildertocId);
        }
        // 微课知识点
        BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isBlank(bookContent)) {
            // 根据课本Id拿到所有目录id
            List<String> listcoContents = yrbcr.findIdByBookId(book);
            // 根据目录Id拿到所有的知识点Id
            Set<Integer> set = new HashSet<>();
            List<Integer> list = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(listcoContents)) {
                List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                set = new HashSet<>(list1);
                list = new ArrayList<>(set);
            }
            if (CollectionUtils.isEmpty(list)) {
                list.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
            // 目录不为空 根据目录找到知识点
        } else {
            List<String> list = yxyResUtil.findTocByTocParent(bookContent);
            List<Integer> knowIds = new ArrayList<Integer>();
            if (CollectionUtils.isNotEmpty(list)) {
                List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                        .findByBookContentIdIn(list);
                knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(knowIds)) {
                knowIds.add(99999);
            }
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
            TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
            TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
            knoBuilder.should(builderknowOne);
            knoBuilder.should(builderknowTwo);
            knoBuilder.should(builderknowThree);
            knoBoolQueryBuilder.must(knoBuilder);
        }
        boolQueryBuilder.should(knoBoolQueryBuilder).minimumNumberShouldMatch(1);
        List<ElasticYxyResResource> list = getList(boolQueryBuilder);
        return list;
    }

    @Override
    public void resDownLoadNumberPlus(String id) {
        YxyResResource resource = yrrr.findById(id);
        if (resource != null) {
            resource.setDownloadCount(resource.getDownloadCount() + 1);
            yrrr.save(resource);
        }

        EsResourceUpdateUtil.updateEsResoure(id);

    }

    @Override
    public ElasticYxyResResource findById(String id) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(id);
        ElasticYxyResResource elasticYxyResResource = et.queryForObject(getQuery, ElasticYxyResResource.class);
        return elasticYxyResResource;
    }

    @Override
    public Page<ElasticYxyResResource> manageSchPlatform(String schoolId, Integer status, String phase, String subject,
            String keyword, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope 本校
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 1);
        boolQueryBuilder.must(builderviewScope);

        // 不查微课的
        TermQueryBuilder builderTypeNot = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(builderTypeNot);

        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 审核状态
        if (status != null && status != -1) {
            TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", status);
            boolQueryBuilder.must(builderStatusYes1);
        }

        // 是否云校资源 isYxYunRes 不是云校资源
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            boolQueryBuilder.must(builder);
        }

        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);

        return page;
    }

    @Override
    public List<ElasticYxyResResource> findByIds(List<String> id) {
        Criteria criteria = Criteria.where("id").in(id);
        CriteriaQuery query = new CriteriaQuery(criteria);
        List<ElasticYxyResResource> list = et.queryForList(query, ElasticYxyResResource.class);
        return list;
    }

    @Override
    public Page<ElasticYxyResResource> manageTeaReachingMyResource(String userId, String schoolId, Integer viewScorp,
            Integer status, String phase, String subject, String keyword, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 上传者
        TermQueryBuilder builderUser = new TermQueryBuilder("uploaderId", userId);
        boolQueryBuilder.must(builderUser);

        // 上传者学校
        TermQueryBuilder builderUploaderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderUploaderSchoolId);

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        if (viewScorp != null && viewScorp != -1) {
            TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", viewScorp);
            boolQueryBuilder.must(builderviewScope);
        }

        // 不查微课的
        TermQueryBuilder builderTypeNot = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(builderTypeNot);
        if (!SystemConstant.YUNXIAO_SCHOOL_ID.equals(schoolId)) {
            // 是否云校资源 isYxYunRes 不是云校资源
            TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
            boolQueryBuilder.must(builderisYxYunRes);
        }

        // 审核状态
        if (status != null && status != -1) {
            // 如果查询已通过 不查询私人的
            if (status == 1) {
                boolQueryBuilder.mustNot(new TermQueryBuilder("viewScope", 0));
            }
            boolQueryBuilder.must(new TermQueryBuilder("status", status));
        }

        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            boolQueryBuilder.must(builder);
        }
        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    @Transactional
    public void updResViewScope(String[] id, Integer viewScope, String userId) {
        List<YxyResResource> list = yrrr.findByIdIn(Arrays.asList(id));
        for (YxyResResource yxyResResource : list) {
            Assert.isTrue(yxyResResource.getViewScope() == 0 ? true : false, "只能分享私有的");
            Assert.isTrue(StringUtils.equalsIgnoreCase(yxyResResource.getUploaderId(), userId) ? true : false,
                    "这不是您的资源");
            yxyResResource.setViewScope(viewScope);
            yxyResResource.setStatus(0);
            yrrr.save(yxyResResource);
        }
    }

    @Override
    @Transactional
    public void delRes(String[] ids, String userId) {
        for (String string : ids) {
            YxyResResource resource = yrrr.findById(string);
            Assert.notNull(resource, "找不到文档，请刷新页面");
            Assert.isTrue(StringUtils.equalsIgnoreCase(resource.getUploaderId(), userId), "这不是您的资源");
            LOGGER.info("****资源之前ID：" + resource.getId() + "****");
            LOGGER.info("****资源之前is_delete：" + resource.getIsDelete() + "****");
            LOGGER.info("****资源之前status：" + resource.getStatus() + "****");
            resource.setIsDelete(1);
            yrrr.save(resource);
        }
    }

    @Override
    public long checkFavor(String userId, String schoolId, String role, String resId) {
        // String plfUserRoleId = plfUserId(userId, role, schoolId);
        // if (plfUserRoleId == null) { return 0; }
        long check = yufr.countByResIdAndUserId(resId, userId);
        return check;
    }

    @Override
    public Page<RespModel> myResourceFavor(String userId, String schoolId, String phase, String subject, String keyword,
            String role, Pageable pageable) throws IllegalAccessException, InvocationTargetException {
        DBCollection dbCollection = mt.getCollection(mt.getCollectionName(YxyUserFavor.class));
        BasicDBObject dbObject = new BasicDBObject("user_id", userId);
        // String plfUserRoleId = plfUserId(userId, role, schoolId);
        // 用户ID
        dbObject.put("user_id", userId);
        // 用户在这个学校的角色ID YxyPlfUserRole
        // dbObject.put("user_role_id", plfUserRoleId);
        // 资源
        dbObject.put("res_type", "00");
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            dbObject.put("phase", phase);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            dbObject.put("subject", subject);
        }
        // 关键字
        if (StringUtils.isNotBlank(keyword)) {
            Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
            dbObject.put("res_name", pattern);
        }

        Page<YxyUserFavorModel> page = MongodbUtil.getPage(dbCollection, dbObject, pageable, YxyUserFavorModel.class);
        List<RespModel> list = new ArrayList<MyCollectSrhController.RespModel>();
        for (YxyUserFavorModel yxyUserFavorModel : page) {
            RespModel model = new RespModel();
            ElasticYxyResResource elasticYxyResResource = findById(yxyUserFavorModel.getRes_id());
            BeanUtils.copyProperties(model, elasticYxyResResource);
            model.setFavorDate(yxyUserFavorModel.getCreated_date() != null
                    ? DateToolUtils.format(yxyUserFavorModel.getCreated_date(), DateToolUtils.FORMAT_SHORT_YMD) : "");
            model.setUploadTimeFormat(elasticYxyResResource.getUploadTime() != null
                    ? DateToolUtils.format(elasticYxyResResource.getUploadTime(), DateToolUtils.FORMAT_SHORT_YMD) : "");
            model.setBookContentNames(elasticYxyResResource.getBookContentNameList());
            list.add(model);
        }
        Page<RespModel> resPage = new PageImpl<MyCollectSrhController.RespModel>(list, pageable,
                page.getTotalElements());
        return resPage;
    }

    @Override
    @Transactional
    public void removeMyResourceFavor(List<String> resIds, String userId, String schoolId, String role) {
        // String plfUserRoleId = plfUserId(userId, role, schoolId);
        // yufr.deleteByResIdInAndUserIdAndUserRoleId(resIds, userId,
        // plfUserRoleId);
        yufr.deleteByResIdInAndUserId(resIds, userId);
    }

    /**
     * 递归获取所有的父级
     */
    private List<YxyResBookContents> loopPids(String bookContentId, List<YxyResBookContents> parent) {
        YxyResBookContents bookContents = yrbcr.findById(bookContentId);
        if (bookContents != null) {
            parent.add(bookContents);
            loopPids(bookContents.getpId(), parent);
        }
        return parent;
    }

    @Override
    @Transactional
    public void teaUpdResource(String userId, String resId, String typeId, String intro, List<String> bookContentNew) {

        YxyResResource resource = yrrr.findById(resId);
        Assert.notNull(resource, "资源不存在");
        resource.setTypeId(typeId);
        resource.setIntro(intro);
        yrrr.save(resource);
        //
        Assert.isTrue(StringUtils.equals(userId, resource.getUploaderId()), "这不是您的资源");
        Assert.isTrue(resource.getViewScope() == 0, "只有是私人的才可以修改");

        // ## 找到资源所有目录
        List<YxyResResourceBookContent> yxyResResourceBookContents = yxyResResourceBookContentRepository
                .findByResourceId(resId);

        List<String> yxyResResourceBookContentIds = yxyResResourceBookContents.stream().map(x -> x.getBookContentId())
                .collect(Collectors.toList());
        // 如果不存在就删除
        for (String string : yxyResResourceBookContentIds) {
            if (!bookContentNew.contains(string)) {
                yxyResResourceBookContentRepository.deleteByResourceIdAndBookContentId(resId, string);
            }
        }
        // 如果不存在就创建
        for (String string : bookContentNew) {
            if (!yxyResResourceBookContentIds.contains(string)) {
                saveResBookContent(resId, string);
            }
        }
    }

    // 资源目录
    @Transactional
    private void saveResBookContent(String resId, String bookContentNew) {
        YxyResResourceBookContent resourceBookContent = yxyResResourceBookContentRepository
                .findByResourceIdAndBookContentId(resId, bookContentNew);
        Assert.isNull(resourceBookContent, "已经和这个目录关联了");
        resourceBookContent = new YxyResResourceBookContent();
        resourceBookContent.setResourceId(resId);
        YxyResBookContents bookContents = yrbcr.findById(bookContentNew);
        Assert.notNull(bookContents, "目录未找到请刷新页面");
        resourceBookContent.setBookContentId(bookContents.getId());
        YxyResBook book = yrbr.findById(bookContents.getBookId());
        Assert.notNull(book, "书籍未找到请刷新页面");
        // # 找到新目录的书
        String subjectName = book.getSubjectName();
        String versionName = book.getVersionName();
        String phaseName = book.getPhaseName();
        String semesterName = book.getSemersterName();

        resourceBookContent.setSubjectId(book.getSubjectId());
        resourceBookContent.setSubjectName(subjectName);
        resourceBookContent.setVersionId(book.getVersionId());
        resourceBookContent.setVersionName(versionName);
        resourceBookContent.setPhaseId(book.getPhaseId());
        resourceBookContent.setPhaseName(phaseName);
        resourceBookContent.setSemesterId(book.getSemersterId());
        resourceBookContent.setSemesterName(semesterName);
        resourceBookContent.setBookId(book.getId());

        List<YxyResBookContents> parentsBookContents = new ArrayList<YxyResBookContents>();
        parentsBookContents = loopPids(bookContentNew, parentsBookContents);
        List<String> pids = parentsBookContents.stream().map(x -> x.getId()).collect(Collectors.toList());
        List<String> pidNames = parentsBookContents.stream().map(x -> x.getName()).collect(Collectors.toList());
        String bookContentPid = StringUtils.join(pids, ",");
        String bookContentPname = StringUtils.join(pidNames, ",");
        Collections.reverse(pidNames);
        String bookContentName = StringUtils.join(pidNames, "-");
        // 名称： 所属 phase + subject + version + bookName(semesterName)
        // + bookcontentName
        String is = phaseName + "-" + subjectName + "-" + versionName + "-" + semesterName + "-" + bookContentName;
        resourceBookContent.setBookContentName(is);

        resourceBookContent.setBookContentPid(bookContentPid);
        resourceBookContent.setBookContentPname(bookContentPname);
        yxyResResourceBookContentRepository.save(resourceBookContent);
    }

    @Override
    public List<ElasticYxyResResource> homeIndexNewResourceTop(String areaId, int size) {
        List<ElasticYxyResResource> elasticYxyResResourcesAlList = new ArrayList<>();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // FIXME(https://yun.91yunxiao.com没有数据) 是否云校资源 isYxYunRes
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        boolQueryBuilder.must(areBuilder);

        //
        TermQueryBuilder notYxWeike = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(notYxWeike);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        List<ElasticYxyResResource> elasticYxyResResources = getListTop(boolQueryBuilder, size, "uploadTime");
        Integer count = 0;
        List<String> idsList = new ArrayList<>();
        if (CollectionUtils.isEmpty(elasticYxyResResources)) {
            count = size;
        } else {
            count = size - elasticYxyResResources.size();
            if (count > 0) {
                elasticYxyResResources.stream().forEach(s -> idsList.add(s.getId()));
            }
            elasticYxyResResourcesAlList.addAll(elasticYxyResResources);
        }
        if (count > 0) {
            BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
            // 刨除已删除的
            TermQueryBuilder builderDel1 = new TermQueryBuilder("isDelete", 0);
            boolQueryBuilder1.must(builderDel1);

            // 类别 viewScope
            TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 2);
            boolQueryBuilder1.must(builderviewScope1);

            TermQueryBuilder notYxWeike1 = new TermQueryBuilder("typeId", "yx14");
            boolQueryBuilder1.mustNot(notYxWeike1);
            // 云校微课
            BoolQueryBuilder boolYun = new BoolQueryBuilder();

            TermQueryBuilder builderisYxYunRes11 = new TermQueryBuilder("isYxYunRes", 1);
            boolYun.should(builderisYxYunRes11);
            // 或者在云校显示
            TermQueryBuilder builderisviewYun1 = new TermQueryBuilder("isYxView", 1);
            boolYun.should(builderisviewYun1);
            boolQueryBuilder1.must(boolYun);

            // 只查询审核已通过的
            TermQueryBuilder builderStatusYes11 = new TermQueryBuilder("status", 1);
            boolQueryBuilder1.must(builderStatusYes11);

            if (CollectionUtils.isNotEmpty(idsList)) {
                // 排除区域的
                TermsQueryBuilder builderidNot = new TermsQueryBuilder("id", idsList);
                boolQueryBuilder1.mustNot(builderidNot);
            }
            List<ElasticYxyResResource> elasticYxyResResources1 = getListTop(boolQueryBuilder1, count, "pv");
            elasticYxyResResourcesAlList.addAll(elasticYxyResResources1);
        }

        return elasticYxyResResourcesAlList;
    }

    @Override
    public List<ElasticYxyResResource> homeIndexResourceTop(String areaId, int size) {
        List<ElasticYxyResResource> elasticYxyResResourcesAll = new ArrayList<>();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // FIXME(https://yun.91yunxiao.com没有数据) 是否云校资源 isYxYunRes
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        //
        TermQueryBuilder notYxWeike = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(notYxWeike);

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        boolQueryBuilder.must(areBuilder);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);
        List<ElasticYxyResResource> elasticYxyResResources = getListTop(boolQueryBuilder, size, "pv");
        Integer count = 0;
        List<String> idsList = new ArrayList<>();
        if (CollectionUtils.isEmpty(elasticYxyResResources)) {
            count = size;
        } else {
            count = size - elasticYxyResResources.size();
            if (count > 0) {
                elasticYxyResResources.stream().forEach(s -> idsList.add(s.getId()));
            }
            elasticYxyResResourcesAll.addAll(elasticYxyResResources);
        }
        if (count > 0) {
            BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
            // 刨除已删除的
            TermQueryBuilder builderDel1 = new TermQueryBuilder("isDelete", 0);
            boolQueryBuilder1.must(builderDel1);

            TermQueryBuilder notYxWeike1 = new TermQueryBuilder("typeId", "yx14");
            boolQueryBuilder1.mustNot(notYxWeike1);
            // 类别 viewScope
            TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 2);
            boolQueryBuilder1.must(builderviewScope1);

            // 云校微课
            BoolQueryBuilder boolYun = new BoolQueryBuilder();

            TermQueryBuilder builderisYxYunRes11 = new TermQueryBuilder("isYxYunRes", 1);
            boolYun.should(builderisYxYunRes11);
            // 或者在云校显示
            TermQueryBuilder builderisviewYun1 = new TermQueryBuilder("isYxView", 1);
            boolYun.should(builderisviewYun1);
            boolQueryBuilder1.must(boolYun);

            // 只查询审核已通过的
            TermQueryBuilder builderStatusYes11 = new TermQueryBuilder("status", 1);
            boolQueryBuilder1.must(builderStatusYes11);

            if (CollectionUtils.isNotEmpty(idsList)) {
                // 排除区域的
                TermsQueryBuilder builderidNot = new TermsQueryBuilder("id", idsList);
                boolQueryBuilder1.mustNot(builderidNot);
            }
            List<ElasticYxyResResource> elasticYxyResResources1 = getListTop(boolQueryBuilder1, count, "pv");
            elasticYxyResResourcesAll.addAll(elasticYxyResResources1);
        }
        return elasticYxyResResourcesAll;
    }

    @Override
    public void addRes(Integer viewScope, String userId, String userNick, String schoolId, String schoolNick,
            List<String> bookContent, String intro, List<ResourceReqModel> resourcemodels, String provinceCode,
            String cityCode, String districtCode) {

        // 作者
        String author = userNick;

        for (ResourceReqModel resourceReqModel : resourcemodels) {
            long size = resourceReqModel.size;

            LOGGER.info("资源信息" + resourceReqModel.toString());
            // 封面
            String cover = null;
            String title = resourceReqModel.title;

            // 根据local获取后缀
            String extension = StringUtils.substringAfterLast(resourceReqModel.location, ".");
            String md5 = resourceReqModel.md5;
            YxyResResource rYxyResResource = null;
            Integer convertStatus = 0;
            List<YxyResResource> md5OrderByUploadTimeAsc = yrrr.findByMd5OrderByUploadTimeAsc(md5);
            if (CollectionUtils.isNotEmpty(md5OrderByUploadTimeAsc)) {
                rYxyResResource = md5OrderByUploadTimeAsc.get(0);
            }

            if (rYxyResResource != null) {
                convertStatus = rYxyResResource.getConvertStatus() == 2 ? rYxyResResource.getConvertStatus() : 0;
            }
            String location = resourceReqModel.location;

            LOGGER.info(resourceReqModel.location + "资源路径" + location);

            String typeId = resourceReqModel.type;
            YxyResType yxyResType = yrtr.findById(typeId);
            Assert.notNull(yxyResType, "类型不存在，请刷新页面");
            String typeName = yxyResType.getName();
            //
            String formatId = "";
            String formatName = "";
            YxyResFormat format = yrfr.findByExtensionContaining(extension.toLowerCase());
            if (format != null) {
                formatId = format.getId();
                formatName = format.getName();
            } else {
                formatId = "FMT06";
                formatName = "其他";
            }
            YxyResResource resource = new YxyResResource();
            resource.setConvertStatus(convertStatus);
            resource.setAuthor(author);
            resource.setCreatedBy(userId);
            resource.setLastModifiedBy(userId);
            resource.setUploaderId(userId);
            resource.setUploaderName(userNick);
            resource.setUploaderSchoolId(schoolId);
            resource.setUploaderSchoolName(schoolNick);
            resource.setIntro(intro);
            resource.setTitle(title);
            resource.setExtension(extension);
            resource.setUploadTime(new Date());
            resource.setMd5(md5);
            resource.setDownloadCount(0l);
            resource.setPv(0L);
            resource.setFavoriteCount(0l);
            resource.setIsDelete(0);
            resource.setFileSize(Integer.parseInt(size + ""));
            Integer status = 0;
            Integer isYxYunRes = 0;
            int isyxView = 0;
            if (StringUtils.equals(schoolId, SystemConstant.YUNXIAO_SCHOOL_ID) && viewScope != 0) {
                // 默认审核通过
                status = 1;
                // 云校资源
                isYxYunRes = 1;
                isyxView = 1;
                viewScope = 2;
            }
            resource.setIsYxYunRes(isYxYunRes);
            resource.setIsYxView(isyxView);
            resource.setStatus(status);
            resource.setConvertStatus(0);
            resource.setViewScope(viewScope);
            resource.setLocation(location);
            resource.setProvinceCode(provinceCode);
            resource.setCityCode(cityCode);
            resource.setDistrictCode(districtCode);
            resource.setMark(0f);
            resource.setCover(cover);
            resource.setTypeId(typeId);
            resource.setTypeName(typeName);
            resource.setFormatId(formatId);
            resource.setFormatName(formatName);
            resource = yrrr.save(resource);
            LOGGER.info(resource.toString());
            for (String bc : bookContent) {
                // 资源目录
                saveResBookContent(resource.getId(), bc);
            }
            EsResourceUpdateUtil.updateEsResoure(resource.getId());
        }
    }

    @Override
    public List<ElasticYxyResResource> findByMd5(String md5) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderDel = new TermQueryBuilder("md5", md5);
        boolQueryBuilder.must(builderDel);
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        List<ElasticYxyResResource> queryForList = et.queryForList(query, ElasticYxyResResource.class);
        return queryForList;
    }

    @Override
    public long resourceNum(SearchResourceModel searchResourceModel) {
        BoolQueryBuilder boolQueryBuilder = get(searchResourceModel);
        BoolQueryBuilder b1 = new BoolQueryBuilder();
        b1.must(boolQueryBuilder);
        // 关键字
        if (StringUtils.isNotBlank(searchResourceModel.keyword)) {
            b1 = keyword(searchResourceModel.keyword, 1, b1);
        }
        long count = countResource(b1);
        if (count == 0 && StringUtils.isNotBlank(searchResourceModel.keyword)) {
            BoolQueryBuilder b2 = new BoolQueryBuilder();
            b2.must(boolQueryBuilder);
            b2 = keyword(searchResourceModel.keyword, 2, b2);
            count = countResource(b2);
            if (count == 0) {
                BoolQueryBuilder b3 = new BoolQueryBuilder();
                b3.must(boolQueryBuilder);
                b3 = keyword(searchResourceModel.keyword, 3, b3);
                count = countResource(b3);
            }
        }
        return count;
    }

    private long countResource(BoolQueryBuilder queryBuilder) {
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
        long count = et.count(query, ElasticYxyResResource.class);
        return count;
    }

    /**
     * 只支持资源查询
     * 
     * @param searchResourceModel
     * @return
     */
    private BoolQueryBuilder get(SearchResourceModel searchResourceModel) {
        BoolQueryBuilder bool = new BoolQueryBuilder();
        String area = searchResourceModel.area;
        String schoolId = searchResourceModel.schoolId;
        Assert.isTrue(!(StringUtils.isNotBlank(area) && StringUtils.isNotBlank(schoolId)), "区域和学校不能一起查出");
        String phaseId = searchResourceModel.phaseId;
        String subjectId = searchResourceModel.subjectId;
        Integer status = searchResourceModel.status;
        Integer viewScope = searchResourceModel.viewScope;
        Integer isYxYunRes = searchResourceModel.isYxYunRes;

        // 是否云校资源
        if (isYxYunRes != null) {
            TermQueryBuilder isYxYunResBuilder = new TermQueryBuilder("isYxYunRes", isYxYunRes);
            bool.must(isYxYunResBuilder);
        }

        // 共享范围
        if (viewScope != null) {
            TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", viewScope);
            bool.must(viewScopeBuilder);
        }
        // 学段
        if (StringUtils.isNotBlank(phaseId) && !StringUtils.equals("all", phaseId)) {
            TermQueryBuilder phaseBuilder = new TermQueryBuilder("phaseIdList", phaseId);
            bool.must(phaseBuilder);
        }
        // 学科
        if (StringUtils.isNotBlank(subjectId) && !StringUtils.equals("all", subjectId)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subjectId);
            bool.must(builder);
        }
        // 状态
        if (status != null) {
            TermQueryBuilder statusBuilder = new TermQueryBuilder("status", status);
            bool.must(statusBuilder);
        }

        // 学校
        if (StringUtils.isNotBlank(schoolId)) {
            TermQueryBuilder statusBuilder = new TermQueryBuilder("uploaderSchoolId", schoolId);
            bool.must(statusBuilder);
        }

        // 区域
        if (StringUtils.isNotBlank(area)) {
            BoolQueryBuilder areBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", area);
            TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", area);
            TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", area);
            areBuilder.should(builderprovince);
            areBuilder.should(buildercity);
            areBuilder.should(builderdistrict);
            bool.must(areBuilder);
            // 如果是查看区域的 只可以查看共享到教育云的。
            TermQueryBuilder publicBuilder = new TermQueryBuilder("viewScope", 2);
            bool.must(publicBuilder);
        }
        // 刨除 微课的
        TermQueryBuilder builderWeike = new TermQueryBuilder("typeId", "yx14");
        bool.mustNot(builderWeike);

        // 只查询未删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        bool.must(builderDel);
        return bool;
    }

    @Override
    public BoolQueryBuilder keyword(String keyword, Integer type, BoolQueryBuilder builder) {
        if (StringUtils.isNotBlank(keyword) && keyword.length() == 1) {
            RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                    SystemConstant.RESOURCE_PREFIX + QueryParser.escape(keyword) + SystemConstant.RESOURCE_SUFFIX);
            builder.must(builderK);
        } else {
            if (type == 1) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword).type(Type.PHRASE);
                builder.must(matchQueryBuilder);
            } else if (type == 2) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword);
                builder.must(matchQueryBuilder);
            } else if (type == 4) {
                RegexpQueryBuilder matchQueryBuilder = new RegexpQueryBuilder("title",
                        SystemConstant.RESOURCE_PREFIX + QueryParser.escape(keyword) + SystemConstant.RESOURCE_SUFFIX);
                builder.must(matchQueryBuilder);
            } else {
                BoolQueryBuilder keywordBoolQueryBuilder = new BoolQueryBuilder();
                String[] key = keyword.split("");
                for (String c : key) {
                    RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                            SystemConstant.RESOURCE_PREFIX + QueryParser.escape(c) + SystemConstant.RESOURCE_SUFFIX);
                    keywordBoolQueryBuilder.should(builderK);
                }
                builder.must(keywordBoolQueryBuilder);
            }
        }

        return builder;
    }

}
